
using System;
using System.Collections.Generic;

using MySql.Data.MySqlClient;

namespace Grr.Models {

	public static class Explore {

		public static void GetPopularAndRecentAndTags(int max_popular, out SearchResult popular,
													  int max_recent, out SearchResult recent,
													  out List<Tag> tags)
		{
			popular = GetPopularResults(max_popular, 0);
			recent = GetRecentResults(max_recent, 0);

			tags = Tag.GetTags();
		}

		public static SearchResult GetPopularResults(int max_results, int start_index)
		{
		List<SearchMatch> matches = new List<SearchMatch>();

		using (MySqlConnection con = DbContext.OpenReadConnection ()) {
			MySqlCommand cmd = new MySqlCommand ("select Grurrahs.name, AVG(user_grurrah_ratings.rating) FROM Grurrahs " +
					"LEFT JOIN user_grurrah_ratings ON Grurrahs.id = user_grurrah_ratings.grurrah_id GROUP BY Grurrahs.name " +
					"ORDER BY AVG(user_grurrah_ratings.rating) DESC LIMIT ?start_index,?max_results", con);
			cmd.Parameters.Add("?max_results", MySqlDbType.Int32).Value = max_results + 1;
			cmd.Parameters.Add("?start_index", MySqlDbType.Int32).Value = start_index;
				
			MySqlDataReader reader = cmd.ExecuteReader ();

			matches = new List<SearchMatch> ();
			while (reader.Read ()) {
				string name = reader.GetString("name");
				int rank = 0;
				if (reader[1] != DBNull.Value)
					rank = reader.GetInt32(1);

				SearchMatch match = new SearchMatch(name, String.Empty, String.Concat("~/grurrahs/", StringUtil.ToFriendlyUri (name)), rank);
				matches.Add(match);
			}
		}

		bool more_available = matches.Count > max_results;
		if (more_available)
			matches.RemoveAt(max_results);

		return new SearchResult(matches, more_available);
		}

		public static SearchResult GetRecentResults(int max_results, int start_index)
		{
			List<SearchMatch> matches;
			using (MySqlConnection con = DbContext.OpenReadConnection())
			{
				MySqlCommand cmd = new MySqlCommand ("select Grurrahs.name FROM Grurrahs ORDER BY updated_time DESC LIMIT ?start_index,?max_results", con);
				cmd.Parameters.Add("?max_results", MySqlDbType.Int32).Value = max_results + 1;
				cmd.Parameters.Add("?start_index", MySqlDbType.Int32).Value = start_index;

				MySqlDataReader reader = cmd.ExecuteReader();

				matches = new List<SearchMatch>();
				while (reader.Read())
				{
					string name = reader.GetString("name");
					int rank = 0;

					SearchMatch match = new SearchMatch(name, String.Empty, String.Concat("~/grurrahs/", StringUtil.ToFriendlyUri (name)), rank);
					matches.Add(match);
				}
			}

			bool more_available = matches.Count > max_results;
			if (more_available)
				matches.RemoveAt(max_results);
			
			return new SearchResult(matches, more_available);
		}
	}
}


